package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	//"encoding/json"
	"github.com/bitly/go-simplejson"
	"strings"
)

const (
	DataRoot     = "./tmp/" // 存放封面图的根目录
	TimeoutLimit = 10       // 设置超时时间
	PageUrl      = "http://api.lovebizhi.com/macos_v4.php?a=category&spdy=1&tid=3&order=hot&color_id=3&device=105&uuid=436e4ddc389027ba3aef863a27f6e6f9&mode=0&retina=0&client_id=1008&device_id=31547324&model_id=105&size_id=0&channel_id=70001&screen_width=1920&screen_height=1200&bizhi_width=1920&bizhi_height=1200&version_code=19&language=zh-Hans&jailbreak=0&mac=&p={pid}"
)

// 壁纸类型，有编号，长宽和URL
type Wallpaper struct {
	Pid    int
	Url    string
	Width  int
	Height int
}

// 将图片下载并保存到本地
func SaveImage(paper *Wallpaper) {
	res, err := http.Get(paper.Url)
	defer res.Body.Close()

	if err != nil {
		fmt.Printf("%d HTTP ERROR:%s", paper.Pid, err)
		return
	}

	//按分辨率目录保存图片
	Dirname := DataRoot + strconv.Itoa(paper.Width) + "x" + strconv.Itoa(paper.Height) + "/"
	if !isDirExist(Dirname) {
		os.Mkdir(Dirname, 0755)
		fmt.Printf("dir %s created\n", Dirname)
	}

	//根据URL文件名创建文件
	filename := filepath.Base(paper.Url)
	dst, err := os.Create(Dirname + filename)
	if err != nil {
		fmt.Println("%d HTTP ERROR:%s", paper.Pid, err)
		return
	}

	// 写入文件
	io.Copy(dst, res.Body)
}

func isDirExist(path string) bool {
	p, err := os.Stat(path)
	if err != nil {
		return os.IsExist(err)
	} else {
		return p.IsDir()
	}
}

func main() {
	//检查并创建临时目录
	if !isDirExist(DataRoot) {
		os.Mkdir(DataRoot, 0755)
		fmt.Println("dir %s created", DataRoot)
	}

	//生成一个数据序列，用来获取分页
	pow := make([]int, 2)
	for i := range pow {
		if i > 0 {
			url := strings.Replace(PageUrl, "{pid}", strconv.Itoa(i), -1)
			fmt.Println(i, url)

			response, err := http.Get(url)

			if err != nil {
				fmt.Println(err)
				continue
			}

			body, _ := ioutil.ReadAll(response.Body)
			js, err := simplejson.NewJson(body)

			//遍历data下的所有数据
			data := js.Get("data").MustArray()
			for _, v := range data {
				v := v.(map[string]interface{})
				for kk, vv := range v {
					if kk == "file_id" {
						//这里 vv 是一个[]interface{} json.Number，不知道怎么取出值，这里用了比较傻的Sprintf
						vv := fmt.Sprintf("%s", vv)
						imgid, _ := strconv.Atoi(vv)
						url := fmt.Sprintf("http://s.qdcdn.com/c/%d,1920,1200.jpg", imgid)

						fmt.Println(kk, imgid, url)

						paper := &Wallpaper{imgid, url, 1920, 1200}
						SaveImage(paper)
					}
				}
			}
		}
	}

	fmt.Println("oh yes, all job done.")
}
